<template>
  <inline-Modal
    :visible="visible"
    :title="menuName"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
    >
      确定
    </a-button>
    <div class="editorPage-container">
      <div class="tabs-card-container">
        <a-tabs type="card" @change="changeTabs($event)">
          <a-tab-pane :key="item.uuid" :tab="item.name" v-for="item in tabs">
          </a-tab-pane>
        </a-tabs>
        <div class="download">
          <input
            @change="importExcel"
            type="file"
            ref="upload"
            id="upload"
            style="display: none"
          />
          <a-button type="primary" icon="cloud-upload" @click="handleUpload()">
            上传
          </a-button>
          <a-button
            type="primary"
            icon="delete"
            @click="handleBatchDeleteFile()"
          >
            批量删除
          </a-button>
        </div>
      </div>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <div class="warp-container">
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="单位名称" prop="unitName">
                <a-input
                  v-model="form.unitName"
                  placeholder="请输入"
                  @change="changeInput($event)"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="上传人">
                <a-input v-model="form.creator" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="上传时间">
                <a-input v-model="form.createTime" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
      <div class="view-container" id="view-container">
        <!-- 文件列表 -->
        <div class="view-list">
          <div class="sub-header">
            文件列表
            <div class="all-select" @click="allClick()">全选</div>
          </div>
          <div class="sub-main">
            <a-empty v-if="fileList.length == 0" :description="false" />
            <template v-else>
              <div
                class="file-item"
                v-for="(item, index) in fileList"
                :key="index"
                :class="[activeIndex == index && 'active']"
              >
                <a-checkbox
                  v-model="item.select"
                  @change="changeItem($event, item)"
                >
                </a-checkbox>
                <div
                  class="icon"
                  :class="[getFileIconName(item.fileName)]"
                ></div>
                <div class="name" @click="handleActiveFile(item, index)">
                  <a-tooltip>
                    <template slot="title">
                      {{ item.fileName }}
                    </template>
                    {{ item.fileName }}
                  </a-tooltip>
                </div>
              </div>
            </template>
          </div>
        </div>
        <!-- 预览区域 -->
        <div class="view-main">
          <div class="tip-name">
            <!-- 文件信息 -->
            <div class="file-info">
              <div class="block">
                <div
                  class="icon"
                  :class="[getFileIconName(currentFile.fileName)]"
                ></div>
              </div>
              <div class="info-content">
                <div class="info-name">{{ currentFile.fileName || "-" }}</div>
                <div class="user">
                  {{ currentFile.creator || "-" }}
                  <div class="drop"></div>
                  {{ currentFile.createTime || "-" }}
                </div>
              </div>
            </div>
            <div class="operate">
              <!-- 下载 -->
              <div
                class="block"
                @click="downloadFile(1)"
                title="下载"
                v-action:dsfzxzx_download
              >
                <a-icon type="download" />
              </div>
              <!-- 全屏 -->
              <div
                class="block"
                :title="isFull ? '退出全屏' : '全屏'"
                @click="!isFull ? handleFullScreen() : exitFullscreen()"
              >
                <a-icon :type="isFull ? 'fullscreen-exit' : 'fullscreen'" />
              </div>
            </div>
          </div>
          <div class="view-container">
            <iframe
              v-if="fileUrl && fileList.length > 0"
              :src="fileUrl"
              frameborder="0"
              id="preFileIframe"
              width="100%"
              height="100%"
            ></iframe>
          </div>
        </div>
      </div>
    </div>
  </inline-Modal>
</template>

<script>
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { axios } from "@/utils/request";
import { getNowDateStr, getFileIconName } from "@/utils/util.js";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { detailCanton, saveCanton } from "@/api/cantonManage";
export default {
  components: {
    IconFont,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        //单位名称
        unitName: "",
      },
      rules: {
        unitName: [
          {
            required: true,
            message: "请输入单位名称",
          },
        ],
      },
      //提交
      submitLoading: false,
      // 页签
      tabs: [],
      activeKey: "",
      //文件列表
      fileList: [],
      activeIndex: 0,
      //选择的文件
      currentFile: {},
      //文件地址
      fileUrl: "",
      //全屏状态
      isFull: false,
      //选中的tab
      currentTabItem: {},
      //复选框
      allChecked: false,
      indeterminate: false,
      checkRowKeys: [],
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    window.addEventListener("resize", () => {
      this.isFull = !!(
        document.webkitIsFullScreen ||
        document.mozFullScreen ||
        document.msFullscreenElement ||
        document.fullscreenElement
      );
    });
  },
  methods: {
    getFileIconName,
    async getData() {
      await this.getDetail();
    },
    //查询详情
    getDetail() {
      detailCanton({
        code: "DSFZX",
      })
        .then((res) => {
          //
          this.tabs = res?.childList ?? [];
          this.tabs.forEach((v) => {
            v.files = JSON.parse(v.files ?? "[]");
          });
          this.currentTabItem = this.tabs?.[0] ?? {};
          this.form = {
            uuid: res.uuid,
            //单位名称
            unitName: this.currentTabItem?.unitName,
            //创建人
            creator: this.currentTabItem.creator,
            //创建时间
            createTime: this.currentTabItem.createTime,
          };
          //
          this.fileList = this.tabs?.[0]?.files ?? [];
          this.currentFile = this.fileList?.[0] ?? {};
          //
          this.fileList.forEach((item) => {
            if (this.checkRowKeys.includes(item.dfsFileUuid)) {
              this.$set(item, "select", true);
            } else {
              this.$set(item, "select", false);
            }
          });
          this.getFileUrl();
        })
        .catch((_) => {});
    },

    changeInput() {
      let { uuid } = this.currentTabItem;
      let index = this.tabs.findIndex((v) => v.uuid == uuid);
      this.tabs[index].unitName = this.form.unitName;
    },

    changeTabs(key) {
      let index = this.tabs.findIndex((v) => v.uuid == key);
      this.currentTabItem = this.tabs[index];
      this.fileList = this.currentTabItem?.files ?? [];
      this.currentFile = this.fileList?.[0] ?? {};
      this.getFileUrl();
      //
      this.form.unitName = this.currentTabItem?.unitName ?? "";
      this.form.creator = this.currentTabItem?.creator ?? "";
      this.form.createTime = this.currentTabItem?.createTime ?? "";
      //
      this.fileList.forEach((item) => {
        if (this.checkRowKeys.includes(item.dfsFileUuid)) {
          this.$set(item, "select", true);
        } else {
          this.$set(item, "select", false);
        }
      });
    },
    //选择文件
    handleActiveFile(item, index) {
      this.activeIndex = index;
      this.currentFile = item;
      this.getFileUrl();
    },
    //预览地址
    getFileUrl() {
      let { url } = this.currentFile;
      this.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let { dfsFileUuid } = row;
      if (checked) {
        this.checkRowKeys.push(dfsFileUuid);
        this.checkRowKeys = Array.from(new Set(this.checkRowKeys));
      } else {
        this.checkRowKeys = this.checkRowKeys.filter((v) => v != dfsFileUuid);
      }
    },

    //全选
    allClick() {
      this.fileList.forEach((v) => {
        this.$set(v, "select", true);
      });
      this.checkRowKeys = this.fileList.map((v) => v.dfsFileUuid);
    },

    //批量删除文件
    handleBatchDeleteFile() {
      if (this.checkRowKeys.length == 0) {
        this.$message.warning("请选择需要删除的文件！");
        return;
      }
      let { uuid } = this.currentTabItem;
      let index = this.tabs.findIndex((v) => v.uuid == uuid);
      this.tabs[index].files = this.tabs[index].files.filter(
        (v) => !this.checkRowKeys.includes(v.dfsFileUuid)
      );
      this.fileList = this.tabs[index].files;
      this.currentFile = this.fileList?.[0] ?? {};
    },

    //上传
    handleUpload() {
      this.$refs.upload.click();
    },
    importExcel(event) {
      let file = event.target.files[0];
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          let { uuid } = this.currentTabItem;
          let index = this.tabs.findIndex((v) => v.uuid == uuid);
          let fileSize = this.sizeTostr(file.size);
          let lastIdx = file.name.lastIndexOf(".");
          let fileType = "." + file.name.substring(lastIdx + 1);
          this.tabs[index].files.push({
            dfsFileUuid: res.dfsFileUuid,
            fileName: file.name,
            select: false,
            url: res.url,
            fileSize,
            fileType,
            creator: this.form.creator,
            createTime: this.form.createTime,
          });
          this.fileList = this.tabs[index].files;
          this.currentFile = this.fileList?.[0] ?? {};
          this.getFileUrl();
        })
        .catch((_) => {})
        .finally((_) => {
          event.target.value = "";
        });
    },
    //文件大小转换
    sizeTostr(size = 0) {
      size = Number(size);
      var data = "";
      if (size < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
      } else if (size < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
      } else if (size < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      var sizestr = data + "";
      var len = sizestr.indexOf("\.");
      var dec = sizestr.substr(len + 1, 2);
      if (dec == "00") {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    },
    //表单提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            uuid: form.uuid,
            //文件
            list: [],
          };
          this.tabs.forEach((item) => {
            const fileList = item.files.map(
              ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
            );
            formJson.list.push({
              uuid: item.detailId,
              name: item.name,
              unitName: item.unitName,
              files: JSON.stringify(fileList),
            });
          });
          this.submitLoading = true;
          saveCanton(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("处理成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "处理失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //下载
    downloadFile(row) {
      const fileList = JSON.parse(row?.fileAddress ?? "[]");
      if (fileList.length == 0) {
        return;
      } else if (fileList.length == 1) {
        let { url } = fileList?.[0] ?? {};
        downloadDfs(url);
      } else {
        this.viewFileModal.name = row.name;
        this.viewFileModal.fileList = fileList ?? [];
        this.viewFileModal.visible = true;
      }
    },

    handelCancel() {
      this.$emit("update:visible", false);
      this.$parent.getDetail();
    },

    //全屏
    handleFullScreen() {
      const element = document.getElementById("view-container");
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
      }
    },

    //退出全屏
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 120px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .editorPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    .warp-container {
      padding-right: 110px;
      box-sizing: border-box;
    }
    .tabs-card-container {
      display: flex;
      /deep/.ant-tabs {
        flex: 1;
        .ant-tabs-nav .ant-tabs-tab {
          margin-right: 8px !important;
          height: 100% !important;
        }
        .ant-tabs-nav-container {
          height: 40px !important;
        }
        .ant-tabs-content {
          display: none;
        }
      }
      .download {
        height: 40px;
        border-bottom: 1px solid #e8e8e8;
        /deep/.ant-btn {
          margin-right: 10px;
          &:last-of-type {
            margin-right: 0;
          }
        }
      }
    }
    .view-container {
      flex: 1;
      border-radius: 4px 4px 4px 4px;
      display: flex;
      overflow: hidden;
      background: #fff;
      .icon {
        width: 18px;
        height: 18px;
        margin: 0 10px;
        flex-shrink: 0;
        &.pdf {
          background: url("~@/assets/img/fileIcon/pdf.png");
          background-size: 100% 100%;
        }
        &.doc {
          background: url("~@/assets/img/fileIcon/doc.png");
          background-size: 100% 100%;
        }
        &.xls {
          background: url("~@/assets/img/fileIcon/xls.png");
          background-size: 100% 100%;
        }
        &.ppt {
          background: url("~@/assets/img/fileIcon/ppt.png");
          background-size: 100% 100%;
        }
        &.image {
          background: url("~@/assets/img/fileIcon/image.png");
          background-size: 100% 100%;
        }
        &.txt {
          background: url("~@/assets/img/fileIcon/txt.png");
          background-size: 100% 100%;
        }
        &.zip {
          background: url("~@/assets/img/fileIcon/zip.png");
          background-size: 100% 100%;
        }
        &.music {
          background: url("~@/assets/img/fileIcon/music.png");
          background-size: 100% 100%;
        }
        &.video {
          background: url("~@/assets/img/fileIcon/video.png");
          background-size: 100% 100%;
        }
        &.annex {
          background: url("~@/assets/img/fileIcon/annex.png");
          background-size: 100% 100%;
        }
        &.cad {
          background: url("~@/assets/img/fileIcon/cad.png");
          background-size: 100% 100%;
        }
      }

      .view-list {
        width: 300px;
        border-radius: 4px 0px 0px 4px;
        border: 1px solid #d4d7d8;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .sub-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px 16px;
          box-sizing: border-box;
          font-size: 16px;
          color: #333333;
          .all-select {
            font-size: 14px;
            color: #1890ff;
            cursor: pointer;
          }
        }
        .sub-main {
          flex: 1;
          overflow: auto;
          position: relative;
          /deep/.ant-empty {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
          .file-item {
            height: 32px;
            padding: 0 16px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #333333;
            margin-bottom: 8px;
            .name {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              cursor: pointer;
            }
            &.active {
              background: rgba(24, 144, 255, 0.1);
              .name {
                color: #1890ff;
              }
            }
          }
        }
      }
      .view-main {
        background: #f7f7f7;
        flex: 1;
        border-radius: 0 4px 4px 0px;
        border: 1px solid #d4d7d8;
        border-left: 0;
        position: relative;
        display: flex;
        flex-direction: column;
        .tip-name {
          height: 64px;
          width: 100%;
          background: #ffffff;
          border-radius: 0px 4px 0px 0px;
          border-bottom: 1px solid #d4d7d8;
          padding: 0 16px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .block {
            width: 32px;
            height: 32px;
            background: #ffffff;
            box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.15);
            border-radius: 4px 4px 4px 4px;
            margin-right: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .file-info {
            display: flex;
            align-items: center;
            .info-content {
              .info-name {
                font-size: 14px;
                color: #333333;
              }
              .user {
                display: flex;
                align-items: center;
                font-size: 12px;
                color: #8a9295;
                .drop {
                  margin: 0 8px;
                  width: 4px;
                  height: 4px;
                  background: #8a9295;
                  border-radius: 10px 10px 10px 10px;
                }
              }
            }
          }
          .operate {
            display: flex;
            align-items: center;
            .block {
              cursor: pointer;
              &:last-of-type {
                margin-right: 0;
              }
            }
          }
        }
        .view-container {
          flex: 1;
        }
      }
    }
  }
}
</style>
